package com.quartz.monitor4job.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.quartz.monitor4job.service.QuartzLogService;

/**
 * 
 * @author LIPENG
 *
 * @date 2017年5月5日 上午11:44:06
 *
 * @version V1.0
 */
public class QuartLogClearThread implements Runnable {

	private static QuartLogClearThread thread = null;
	private static boolean isInit = false;

	public static synchronized QuartLogClearThread getInstance() {
		if (!isInit && thread == null) {
			thread = new QuartLogClearThread();
			isInit = true;
			return thread;
		}
		return thread;
	}

	public static boolean isInit() {
		return isInit;
	}

	private static final Logger logger = LoggerFactory.getLogger(QuartLogClearThread.class);

	/**
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		updateNonStop();
		int loadDay = QuartzUtils.getKeeyDay();
		while (true) {
			try {
				Thread.sleep(24 * 60 * 60 * 1000);
				getService().delete(loadDay);
			} catch (Exception e) {
				logger.error("清理" + loadDay + "天前的job日志数据出错", e);
			}
		}

	}

	private void updateNonStop() {
		logger.info("开始更新由于重启而没有更新状态的job");
		try {
			getService().updateUnStop();
		} catch (Exception e) {
			logger.error("更新由于重启而没有更新状态的job出错",e);
		}
		logger.info("结束更新由于重启而没有更新状态的job");
	}

	private QuartzLogService getService() {
		return (QuartzLogService) ApplicationUtil.getBean("quartzLogService");
	}
}